<?php
declare (strict_types = 1);

namespace app\admin\controller\login;

use app\admin\service\login\IndexService;
use app\admin\validate\Login;
use app\common\controller\AdminBase;
use hg\apidoc\annotation as Apidoc;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Session;

/**
 * @Apidoc\Title("登录管理")
 */
class Index extends AdminBase
{
    /**
     * @Apidoc\Title("1.0 登录验证信息")
     * @Apidoc\Url("blog_admin/v1/admin/login_verify")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("time", type="string", desc="时间戳")
     * @Apidoc\Returned("key", type="string", desc="值")
    */
    public function get_verify()
    {
        $time = round(microtime(true) * 1000); // 使用 microtime() 函数获取当前时间（单位为秒）并乘以 1000，然后四舍五入得到毫秒时间戳
        $uniqid = uniqid((string)mt_rand(10000,999999)); //唯一标识
        $rs = Captcha::create(); //创建验证码图片
        $base64_img = "data:image/png;base64,".base64_encode($rs->getData());//图片转为64位数据流
        $key = Session::get('captcha.key');//验证码的key缓存
        cache('ADMIN_LOGIN_VERIFY_'.$uniqid,$key); //加入缓存
        $data = [
            'captcha' => $base64_img,
            'uniqid'=>$uniqid,
            'token' => $this->request->buildToken('adminLogin', sha1($time . '_MyBlog')),//创建token
        ];
        return suc('成功', $data);
    }

    /**
     * @Apidoc\Title("1.0 管理员登录")
     * @Apidoc\Url("blog_admin/v1/admin/login")
     * @Apidoc\Method("POST")
     * @Apidoc\Query("uniqid", type="string",require=true, desc="缓存标识",default="")
     * @Apidoc\Query("username", type="string",require=true, desc="账号",default="")
     * @Apidoc\Query("pwd", type="string",require=true, desc="密码",default="")
     * @Apidoc\Query("verifyCode", type="string",require=true, desc="验证码")
     * @Apidoc\Returned("time", type="string", desc="时间戳")
     * @Apidoc\Returned("key", type="string", desc="值")
     */
    public function admin_login()
    {
        // 判断是否是POST请求
        if ($this->request->isPost()) {
            try {
                //校验验证数据
                $data = reqDecode();
               $ischeck =  validate(Login::class)->check($data);
               if(!$ischeck){return suc('非法请求','',0);}
                //校验验证码
                $captcha = cache('ADMIN_LOGIN_VERIFY_'.$data['uniqid']);
                if($captcha && password_verify(mb_strtolower($data['verifyCode'], 'UTF-8'), $captcha)){
                    cache('ADMIN_LOGIN_VERIFY_'.$data['uniqid'],null); //清除缓存
                }else{
                    return suc('验证码错误','',0);
                }
                //判断 登录账号 是否规范
                if (empty($this->escapeString($data['username']))) {
                    return suc('非法操作','',0);
                }

                $res = IndexService::adminLogin($data);
                return $res;
            } catch (\think\exception\ValidateException $e) {
                // 验证失败 输出错误信息
                return suc($e->getError(),'',0);
            }
        } else {
            return suc('非法操作','',0);
        }
    }
    /**
     * @Apidoc\Title("1.0 退出登录")
     * @Apidoc\Url("blog_admin/v1/login/admin/logout")
     * @Apidoc\Method("get")
     * @Apidoc\Returned("time", type="string", desc="时间戳")
     * @Apidoc\Returned("key", type="string", desc="值")
     */
    public function logout()
    {
        Session::clear();
        Cache::clear();
        return suc('成功退出','');
    }

}
